const path = require("path");
const swaggerJSDoc = require("swagger-jsdoc");
const { koaSwagger } = require("./local/koa2-swagger-ui");

const options = {
  definition: {
    openapi: "3.0.0",
    info: {
      title: "我是标题",
      version: "1.0.0",
      description: "我是描述",
    },
    //servers的每一项，可以理解为一个服务,实际项目中，可自由修改
    servers: [
      {
        url: "/api",
        description: "API server",
      },
    ],
  },
  apis: [path.join(process.cwd(), "/src/router/*.js")],
};

const swaggerSpec = swaggerJSDoc(options);

// 如果有Swagger规范文件转TS的需求，可在此处保留Swagger规范文件到本地，方便使用
//fs.writeFileSync('swagger.json', JSON.stringify(swaggerSpec, null, 2));
exports.swaggerSpec = swaggerSpec;

// 封装koaSwagger完成打包单JS文件
function defindKoaSwagger(params = {}) {
  // 保存原__dirname
  const olddirname = __dirname;
  // 将插件koa2-swagger-ui本地封装一次：src/local/koa2-swagger-ui
  __dirname = path.join(process.cwd(), "/src/local/koa2-swagger-ui/");
  // swaggerVersion是根据 koa2-swagger-ui/package.json 中 swagger-ui-dist
  const result = koaSwagger({ ...params, swaggerVersion: "5.9.0" });
  // 恢复原__dirname
  __dirname = olddirname;
  return result;
}

exports.defindKoaSwagger = defindKoaSwagger;
